//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include "CHandwriting.h"

Int32 g_head;
Int32 g_tail;
wchar_t g_candidateBuffer[HANDWRITING_BUFFERSIZE][11];

DzEvent g_handwritingEvent;

CHandwriting::CHandwriting()
{
    g_head = 0;
    g_tail = 0;
}

ECode CHandwriting::Read(
    /* [in] */ Int64 offset,
    /* [in] */ Int32 bytesToRead,
    /* [out] */ MemoryBuf* pBuffer,
    /* [out] */ IEvent** ppCompletionEvent)
{
    WaitResult wr;
    EventState state;
    wchar_t* candidate = (wchar_t*)pBuffer->GetPayload();

    while (g_head == g_tail) {
        g_handwritingEvent.Wait(&wr, &state);

        if (wr == WaitResult_Interrupted) {
            return NOERROR;
        }
    }

    int i = 0;
    while (g_candidateBuffer[g_tail][i] != L'\0') {
        *candidate = g_candidateBuffer[g_tail][i];
        i++;
        candidate++;
    }
    *candidate = L'\0';

    g_tail = (g_tail + 1) % HANDWRITING_BUFFERSIZE;

    return NOERROR;
}

ECode CHandwriting::Control(
    /* [in] */ Handle32 controlCode,
    /* [in] */ const MemoryBuf &inBuffer,
    /* [out] */ MemoryBuf* pOutBuffer,
    /* [out] */ IEvent** ppCompletionEvent)
{
    return NOERROR;
}

EXTERN IDeviceDriver * CDECL CreateHandwriting(uint_t uDeviceNo, void *pvParameter)
{
    CHandwriting* handwriting = new CHandwriting;
    if (!handwriting) {
        DRV_EXPRESSION(ERRORLEVEL, kprintf("not enough memory\n"));

        return NULL;
    }

    return handwriting;
}
